// 包含头文件
#include "DHT.h"
#define DHTPIN 2
//2号作为温湿度传感器的引脚    
#define DHTTYPE DHT11  
//指明传感器类型 DHT11
DHT dht(DHTPIN, DHTTYPE);
#include <LiquidCrystal.h> 
// 初始化引脚
#define printByte(args) write(args);
LiquidCrystal lcd(12, 11, 6, 5, 4, 3); 
//自定义摄氏度的字符
uint8_t sheshidu[8]={0x08,0x14,0x08,0x07,0x04,0x04,0x04,0x07,};
//自定义百分号 %
uint8_t wenleft[8] = {0x1D,0x15,0x1D,0x06,0x0C,0x17,0x15,0x17,};
int kai = 8;
int inputPin = 9;
//int jiance = 10;
int LEDState = HIGH;
// 当前 LED 状态
int buttonState; // 读取的当前按键状态
int lastButtonState = LOW; // 上次读取的按键状态

long debouncetime = 50;
long lastDebounceTime = 0;
int temp = 1;
void setup() { 
 // 设置行列值
 lcd.begin(16, 2); 
 pinMode(kai,OUTPUT);
 pinMode(inputPin,INPUT);
 pinMode(jiance,INPUT);
 digitalWrite(kai,HIGH);
 //初始化温湿度传感器 串口通信
 Serial.begin(9600);
 Serial.println("test!");
 dht.begin();
 //创建自定义字符的编号
 lcd.createChar(0,sheshidu);
 lcd.createChar(1,wenleft);
 lcd.noDisplay();
} 
void loop() 
{ 
  int reading = digitalRead(inputPin);
   delay(200);
  Serial.println(reading);


   if (reading != lastButtonState) { 
 // 复位去抖时间，就是把当前时间保存下来
 lastDebounceTime = millis(); 
 } 
 if ((millis() - lastDebounceTime) > debouncetime) { 
 // 等过了去抖时间，再次去检测按键的状态
 if (reading != buttonState) {
   buttonState = reading; 
 // 如果按键仍然保持上次的状态，则认为这个按键按下是真实有效的
 if (buttonState == HIGH) { 
 LEDState = !LEDState; 
 } 
 } 
 }
 digitalWrite(kai, LEDState); 
 // 保存当前值，一边下一个循环检测的时候使用
 lastButtonState = reading; 

 int reading2 = digitalRead(jiance);
 if(reading2 == HIGH)
 {
        lcd.display();
        Serial.println("right");
        delay(15);
 }
 else
 {
        lcd.noDisplay();
        Serial.println("OK");
        delay(15);
 }
  /*if(reading == HIGH )
  {
    lasttime = millis();
    if((millis()-lasttime) > debouncetime)
    {
      if(reading == HIGH && temp == 1)
      {
        temp = -temp;
        lcd.display();
        Serial.println("right");
        delay(15);
      }
      else if(reading == HIGH && temp == -1)
      {
        temp = -temp;
        lcd.noDisplay();
        Serial.println("OK");
        delay(15);
      }
      
    }
  }*/
  // error
  Serial.println("temp: ");
  Serial.println(temp);

  float h = dht.readHumidity();
  float t = dht.readTemperature(); 
  //判断是否为空值，以保证数值有效
  if (isnan(h) || isnan(t)) 
  {
    Serial.println("Failed to read from DHT sensor!");
    lcd.print("Error!");
    return;
  }
  //光标设置在最前面
  //以下皆是在屏幕上的打印内容
  lcd.setCursor(0,0);
  lcd.print("Humidity: ");
  lcd.print(h);
  lcd.write(byte(1));
  lcd.setCursor(0,1);
  lcd.print("T: ");
  lcd.print(t);
  lcd.write(byte(0));
  Serial.println(h);
  Serial.println(t); 
 

}
